import { Element, render, setAttr } from "./element";
let allPatches;
let index = 0
function patch(node, patches) {
  allPatches = patches
  // 递归树 给元素打补丁
  treeWalker(node)
}

function treeWalker(node) {
  index += 1
  let curPatch = allPatches[index]
  let childNodes = node.childNodes;
  // console.log("curPatch=", curPatch, index, childNodes);
  // console.log("index=", index);
  // console.log("curPatch=", curPatch);
  // console.log('childNodes=', childNodes);
  [...childNodes].forEach(child => treeWalker(child))
  // 递归找到最深的节点， 从最深节点开始向外层打补丁
  if (curPatch) {
    doPatch(node, curPatch)
  }
}

function doPatch(node, patches) {
  // console.log(node, patches);
  patches.forEach(patch => {
    switch (patch.type) {
      case 'ATTRS':
        // node.removeAllAttributes()
        for (const key in patch.attrs) {
          let value = patch.attrs[key]
          if (value) {
            setAttr(node, key, value)
          } else {
            node.removeAttribute(key)
          }
        }
        break;
      case 'TEXT':
        node.textContent = patch.text
        break;
      case 'REPLACE':
        let newNode = (patch.newNode instanceof Element)
          ? render(patch.newNode)
          : document.createTextNode(patch.newNode)
        console.log("newNode=", newNode);
        // 替换节点
        node.parentNode.replaceChild(newNode, node)
        break;
      case 'REMOVE':
        node.parentNode.removeChild(node)
        break;
      case 'CREATE_NODE':
        // let newTagNode = render(patch.newNode)
        [...patch.newNode].forEach(el => {
          let newNode = (el instanceof Element)
            ? render(el)
            : document.createTextNode(el)
          node.parentNode.appendChild(newNode)
        })
        console.log('CREATE_NODE 节点', patch.newNode, node, node.parentNode);
        // node.parentNode.parentNode.appendChild(newTagNode)
        break;
      case 'CREATETAGNODE':
        let newTagNode = render(patch.newNode)
        console.log('CREATETAGNODE 标签节点');
        node.parentNode.parentNode.appendChild(newTagNode)
        break;
      case 'CREATETEXTNODE':
        let newTextNode = document.createTextNode(patch.newNode)
        console.log('CREATETEXTNODE 文本节点');
        node.parentNode.appendChild(newTextNode)
        break;
      default:
        break;
    }
  })
}


export default patch